import { useCallback, useEffect, useMemo, useRef } from 'react';
import TreeView from 'devextreme-react/tree-view';

import ContextMenu from 'devextreme-react/context-menu';
import React from 'react';

// export interface TreeProps {
//     onMenuItemCliecks: (item: any) => void;
//     menuItems?: () => void;
//     treeViewItemContextMenu: (e: any) => void;
//     contextMenuItemClick: (e: any) => void;
//     onItemClick?: (e: any) => void;
//     data: any;
//     width?: string
// }

const PublicTree = (props: any) => {
    const {
        data,
        // 右键菜单单击事件
        onMenuItemCliecks,
        // menu 数据
        menuItems,
        // 右键菜单
        treeViewItemContextMenu,
        onItemClick,
        width,
        ...restProps
    } = props

    const TreeViewRef = useRef<any>()
    const contextMenuRef = useRef<ContextMenu>(null);

    useEffect(() => {
        contextMenuRef
    }, [])

    // // 右键菜单单击事件 e MenuItem
    const contextMenuItemClick = useCallback(async (e: any) => {
        switch (e.itemData.id) {
            case 'show': {
                TreeViewRef.current.instance.expandAll()
                break;
            }
            case 'closed': {
                TreeViewRef.current.instance.collapseAll()
                break;
            }
        }
        onMenuItemCliecks({ itemID: e.itemData.id, data: e.itemData });
    }, [])

    const PublicTree = (data: any) => {
        return (
            <>
                <TreeView
                    {...restProps}
                    width={width}
                    id='PublicTree'
                    ref={TreeViewRef}
                    selectionMode='single'
                    selectByClick={true}
                    dataSource={data}
                    dataStructure="plain"
                    displayExpr='text'
                    parentIdExpr='pid'
                    keyExpr='id'
                    searchMode="contains"
                    rootValue='all'
                    searchEnabled={true}
                    searchEditorOptions={{
                        placeholder: ''
                    }}
                    onItemContextMenu={(e: any) => treeViewItemContextMenu(e)}
                    onItemClick={(e: any) => onItemClick(e)}
                />
            </>
        )
    }

    const Menu = (menuData: any) => {
        return (
            <ContextMenu
                ref={contextMenuRef}
                dataSource={menuData()}
                target="#PublicTree .dx-treeview-item"
                onItemClick={contextMenuItemClick}
            />
        );
    };

    return (
        <>
            {useMemo(() => {
                return PublicTree(data)
            }, [data])
            }

            {
                Menu(menuItems)
            }

        </>
    )
}

export default React.memo(PublicTree)